package com.awesome.spring.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.awesome.spring.bean.Account;
import com.awesome.spring.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * AccountController
 *
 * @author alex
 * @date 2023/10/13
 */
@RequestMapping("/account")
@RestController
public class AccountController {

    @Autowired
    private AccountService accountService;

    @GetMapping("/find")
    public String find() throws JsonProcessingException {
        Account account = accountService.list().get(0);
        ObjectMapper objectMapper = new ObjectMapper();
        String res = objectMapper.writeValueAsString(account);
        System.out.println(res);
        return res;
    }

    @RequestMapping("/reduce")
    public String debit(String userId, int money) {
        try {
            accountService.reduce(userId, money);
            return "扣款成功";
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return "扣款失败";
        }
    }
}
